package DynamicProgramming.Medium;

public class LC0072 {
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1]; // dp[i,j]是word1[0~i]转到word2[0~j]所需的最少步数
        for (int i = 0; i <= m; i++) dp[i][0] = i; // word1[0~i]转到空字符串，只需删除各个字符
        for (int i = 0; i <= n; i++) dp[0][i] = i;

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1]; // 如果word1[i]==word2[j]，只需考虑前面的字符
                else {
                    int tmp = Math.min(dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1); // +1表示替换/删除字符
                    dp[i][j] = Math.min(tmp, dp[i][j - 1] + 1); // +1表示插入字符
                }
            }
        }

        return dp[m][n];
    }
}
